#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Project: spd-dict-traverse

import sys
import os
import json
import re

IMG_PATTERN = re.compile('https?://(?P<URLSCHEMA>[^/]+)/(?P<FILEPATH>\S+)/(?P<FILENAME>[^/]+\.(jpg|png|jpeg))$', re.I)
URLSCHEMA = 'http://images.baixingliangfan.cn/'

def list_dictionary(d, n_tab=-1, *args, **kwargs):
    if isinstance(d, list):
        for i in d:
            kwargs['source_list'] = list_dictionary(i, n_tab, source_list=kwargs['source_list'])
    elif isinstance(d, dict):
        n_tab += 1
        for key, value in d.items():
            tup1 = ()
            #print("{}key:{}".format("\t" * n_tab, key))
            if key == 'image' or key == 'PICTURE_ADDRESS':
                tup1 = tup1 + (key,)
            kwargs['source_list'] = list_dictionary(value, n_tab, source_list=kwargs['source_list'], tup1=tup1)
    else:
        #print("{}{}".format("\t" * n_tab, d))
        if len(kwargs['tup1']) > 0:
            file_name = extract_image_name(d)
            if file_name != '':

                kwargs['tup1'] = kwargs['tup1'] + (d, file_name)
                kwargs['source_list'].append(kwargs['tup1'])
    return kwargs['source_list']


def load_json_file_dict(file_name):
    p = r"./{}".format(file_name)
    if os.path.exists(p):
        if sys.version_info.major > 2:
            f = open(p, 'r', encoding='utf-8')
        else:
            f = open(p, 'r')
        dict_data = json.load(f)
        # or
        # dict_data = json.loads(f.read())
        # print(dict_data)
        return dict_data


def extract_image_name(url):
    filename = ''
    if IMG_PATTERN.search(url):
        t = IMG_PATTERN.search(url).groupdict()
        print("URLSCHEMA:" + t["URLSCHEMA"])
        print("FILEPATH:" + t["FILEPATH"])
        print("FILENAME:" + t["FILENAME"])
        filename = t["FILENAME"]
    return filename


if __name__ == '__main__':
    source_list = []
    dict_data = load_json_file_dict('data.json')
    source_list = list_dictionary(dict_data, n_tab=-1, source_list=source_list)
    print(source_list)
